<script setup lang="ts">
import SettingsSection from "@/components/settings/settings-section.vue";
import { useProjectStore } from "@/modules/local-project/project-store.ts";
import { reactive, toRaw } from "vue";
import { hc } from "@/framework/vue/util/render.ts";
import { ArrowDownOutlined, ArrowUpOutlined, DeleteOutlined, FolderAddOutlined } from "@ant-design/icons-vue";
import { noop } from "@/framework/util/warning.ts";
import { isSameArray } from "@/framework/util/arrays.ts";

const project = useProjectStore();

const formState = reactive({
  scanFolders: [] as string[],
});

const setDefaultValue = () => {
  formState.scanFolders = [...project.scanFolders];
};

const saveValue = () => {
  const values = [...toRaw(formState.scanFolders)];
  // console.log("save value =>", values, project.scanFolders);
  if (!isSameArray(values, project.scanFolders)) {
    project.setScanFolders(values);
    project.loadProjects();
  }
};

const pickScanFolder = () => {
  native.dialog
    .showOpenDirectoryDialog({ title: "选择扫描目录" })
    .then(ret => {
      if (!ret.canceled) {
        for (const filePath of ret.filePaths) {
          if (!formState.scanFolders.includes(filePath)) {
            formState.scanFolders.push(filePath);
          }
        }
      }
    })
    .catch(noop);
};

const deleteScanFolder = (folder: string) => {
  formState.scanFolders = formState.scanFolders.filter(item => item !== folder);
};

const moveUp = (folder: string) => {
  const index = formState.scanFolders.indexOf(folder);
  if (index > 0) {
    const temp = formState.scanFolders[index - 1];
    formState.scanFolders[index - 1] = folder;
    formState.scanFolders[index] = temp;
  }
};
const moveDown = (folder: string) => {
  const index = formState.scanFolders.indexOf(folder);
  if (index < formState.scanFolders.length - 1) {
    const temp = formState.scanFolders[index + 1];
    formState.scanFolders[index + 1] = folder;
    formState.scanFolders[index] = temp;
  }
};
</script>

<template>
  <settings-section :model="formState" :set-default-value="setDefaultValue" :save-value="saveValue">
    <a-form-item label="扫描路径">
      <template v-for="(it, i) in formState.scanFolders" :key="it">
        <div class="flex col-gap-10 mb-10">
          <div class="flex-1">
            <a-input readonly :value="it" />
          </div>
          <a-button :icon="hc(ArrowUpOutlined)" :disabled="i === 0" @click="moveUp(it)" />
          <a-button :icon="hc(ArrowDownOutlined)" :disabled="i === formState.scanFolders.length - 1" @click="moveDown(it)" />
          <a-button :icon="hc(DeleteOutlined)" @click="deleteScanFolder(it)" />
        </div>
      </template>
      <a-button :icon="hc(FolderAddOutlined)" @click="pickScanFolder">添加</a-button>
    </a-form-item>
  </settings-section>
</template>

<style scoped lang="less"></style>
